package com.lesent.kafka.config;

import com.lesent.kafka.service.IZookeeperService;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.IOException;
import java.util.Properties;

/**
 * @author shengtao
 * @Description:
 * @date 2018/12/19 16:23
 */
@Configuration
@AutoConfigureAfter(ZookeeperConfig.class)
public class KafkaConfig {

    @Autowired
    private IZookeeperService zookeeperService;

    //生产者
    @Bean
    public Producer<String, String> producer(){
        Properties properties = new Properties();
        try {
            zookeeperService.test();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            properties.load(new PathMatchingResourcePatternResolver().getResource("classpath:kafka-producer.properties").getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(0);
        }
        Producer<String,String> producer = new KafkaProducer<String, String>(properties);
        return producer;
    }

    //消费者
    @Bean
    public KafkaConsumer<String, String> kafkaConsumer(){
        Properties properties = new Properties();
        try {
            properties.load(new PathMatchingResourcePatternResolver().getResource("classpath:kafka-consumer.properties").getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(0);
        }
        KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<String, String>(properties);
        return kafkaConsumer;
    }
}
